import { ref, reactive, toRefs } from "vue";

type paginationParams = {
  pageNum: number;
  pageSize: number;
};

export default function useTable<
  T extends { list: any[]; total: number },
  P extends paginationParams
>(fn: (params: P) => RES<T>, searchParams?: Object) {
  // 固定的部分，分页参数
  const params = reactive<paginationParams>({
    pageNum: 1,
    pageSize: 10,
  });

  const list = ref<T["list"]>([]);
  const total = ref(0);

  const fetch = () => {
    fn({ ...(params as P), ...searchParams }).then((res) => {
      if (res.code === 200) {
        // 保存数组
        list.value = res.data.list;
        // 保存总数
        total.value = res.data.total;
      }
    });
  };
  fetch();

  //   准备多个不同的函数以应对不同的情况下调用
  const pageChangeHandle = () => {
    // 如果还想实现别的逻辑，可以继续扩展
    fetch();
  };

  const pageSizeChangeHandle = () => {
    // 如果还想实现别的逻辑，可以继续扩展
    fetch();
  };

  const searchHandle = () => {
    fetch();
  };
  return {
    list,
    total,
    ...toRefs(params),
    pageChangeHandle,
    pageSizeChangeHandle,
    searchHandle,
  };
}
